/**
 * Created by wry on 2014/12/15.
 */

var systemService = require('../services/systemService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var qiniuUtil = require('../common/utils/qiniuUtil');
var questionService = require('../services/questionService');
var moment = require('moment');
var md5 = require('MD5');

exports.getWeather = function (req, res) {
    var lat = req.params.latitude;
    var lon = req.params.longitude;

    systemService.getWeatherService(lat, lon, function (err, data) {
        if (err) {
            logger.error("Failed to get the community List by coordinates ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to get the community List by coordinates ! " + err.message));
        }
        else {
            // 返回消息
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.searchTerms = function (req, res) {
    var keyword = req.params.keyword;
    var token = req.params.token;

    systemService.searchTermsService(token, keyword, function (err, results) {
        if (err) {
            logger.error("Failed to search terms ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to search terms ! " + err.message));
        }
        else {
            // 返回消息
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.searchQuestionAndReply = function (req, res) {
    var keyword = req.params.keyword;
    var token = req.params.token;

    systemService.searchQuestionAndReplyService(keyword, token, function (err, results) {
        if (err) {
            logger.error("Failed to search question and reply ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to search question and reply ! " + err.message));
        }
        else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.searchTopic = function (req, res) {
    var keyword = req.params.keyword;
    var token = req.params.token;

    systemService.searchTopicService(keyword, token, function (err, results) {
        if (err) {
            logger.error("Failed to search searchTopic ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to search searchTopic! " + err.message));
        }
        else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.globalSearch = function (req, res) {
    var keyword = req.params.keyword;
    var token = req.params.token;

    systemService.globalSearchService(keyword, token, function (err, result) {
        if (err) {
            logger.error("Failed to search globalSearchService ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                users: result[0].users,
                userNum: result[0].userNum,
                questions: result[1].questions,
                questionNum: result[1].questionNum
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.searchUser = function (req, res) {
    var token = req.params.token;
    var page = req.params.page;
    var keyword = req.params.keyword;

    systemService.searchUserService(keyword, page, token, function (err, result) {
        if (err) {
            logger.error("Failed to search searchUserService ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                users: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.searchUgc = function (req, res) {
    var token = req.params.token;
    var page = req.params.page;
    var keyword = req.params.keyword;

    systemService.searchUgcService(keyword, page, token, function (err, result) {
        if (err) {
            logger.error("Failed to search searchUgcService ! " + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                questions: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.searchAppUgc = function (req, res) {
    var token = req.params.token;
    var page = req.params.page;
    var keyword = req.body.keyword;

    if (keyword == null) {
        logger.error("Failed to  searchAppUgc ! 无关键字");
        var data = {
            ugcList: []
        };
        res.json(messageUtil.composeSucceededMessage(req, null, data));
    } else {
        systemService.searchAppUgcService(keyword, page, token, function (err, result) {
            var data = {
                ugcList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        })
    }
};

/***
 * 更新版主管理-帖子查询接口
 * @param req
 * @param res
 */
exports.searchAppQuestionNew = function (req, res) {
    var token = req.params.token;
    var page = req.params.page;
    var keyword = req.body.keyword;

    <!--  宝宝树66小区二次改造    add   gct  20170808   start   -->
    var flag=req.params.flag;
    var communityId=req.params.communityId;
    <!--  宝宝树66小区二次改造    add   gct  20170808   end   -->

    if (keyword == null) {
        logger.error("Failed to  searchAppUgc ! 无关键字");
        var data = {
            ugcList: []
        };
        res.json(messageUtil.composeSucceededMessage(req, null, data));
    } else {
        systemService.searchAppQuestionService(keyword, page, token,flag,communityId, function (err, result) {
            var data = {
                ugcList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        })
    }
};

/**
 * system-controller.js
 *创建banner
 *author：chenjinzhuan
 * */
exports.createBanner = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    var input = JSON.stringify(req.body);
    input = JSON.parse(input);

    //console.log(input);
    //console.log(input.stickyPage);
    //console.log(input.banner);

    systemService.createBannerService(id, input, function (err, banner) {
        if (err) {
            logger.error("Failed to create banner - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to create banner - " + err.message));
        } else {
            logger.debug("Succeeded to create a banner - " + banner._id);
            res.json(messageUtil.composeSucceededMessage(req, null, {"objId": banner._id}));
        }
    });
};

/**
 * system-controller.js
 *上传banner图片
 *author：chenjinzhuan
 * */
exports.uploadBannerBgImages = function (req, res) {
    var objectName = 'system_BannerDefinitions';
    var id = req.params.bannerObjId;

    toolUtil.uploadImageService(objectName, id, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload bannerBgImages... - ' + err.message));
        } else {
            var tempImages = new Array();
            var displayOrder = new Array();
            var k = 0;
            for (i = 0; i < images.length; i++) {
                if (images[i] != null) {
                    displayOrder[i] = i + 1;
                    tempImages[k++] = {
                        "displayOrder": i + 1,
                        "backgroundImageURL": images[i]
                    }
                }

            }
            systemService.setImagesToBannerService(id, tempImages, function (err, result) {
                if (err || images == null) {
                    res.json(messageUtil.composeFailedMessage(req, 'Failed to upload bannerBgImages... - ' + err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null));
                }
            });
        }
    })
};

/**
 * system-controller.js
 *修改banner
 *author：chenjinzhuan
 * */
exports.updateBanner = function (req, res) {
    var id = req.params.bannerObjId;
    var userId = toolUtil.getUserObjIdByToken(req.params.token);
    var input = req.body;
    //var input = JSON.stringify(req.body);
    //console.log(input);
    //var input = JSON.parse(input);
    //console.log(input);
    input.lastModifiedBy = userId;
    console.log(input);
    logger.debug('Updating a Banner: ' + id);

    systemService.updateBannerService(id, input, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to update the banner data...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the banner data...!'));
        } else {
            console.log(results);
            if (results[0][0] != 0 && results[1][0] != 0) {
                logger.debug("Update banner successfully...!");
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            } else {
                logger.error('Failed to update the banner, banner is not existing! -' + id);
                res.json(messageUtil.composeFailedMessage(req, 'Failed to update the banner, banner is not existing! -' + id));
            }
        }
    });
};

/**
 * system-controller.js
 *删除banner
 *author：chenjinzhuan
 * */
exports.deleteBanner = function (req, res) {
    var id = req.params.bannerObjId;

    systemService.deleteBannerService(id, function (err) {
        if (err) {
            console.log(err.message);
            logger.error('Exception happened when Remove banner...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when Remove banner...!'));
        } else {
            logger.debug('Remove to contactlist successfully...!');
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * system-controller.js
 *获取指定的banner
 *author：chenjinzhuan
 * */
exports.getBanner = function (req, res) {
    var stickyPage = req.params.stickyPage;
    var token = req.params.token;
    logger.debug('Get banner.... - ' + stickyPage);

    systemService.getBannerService(token, stickyPage, function (err, banner) {
        if (err) {
            logger.error('Exception happened when get banner list...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get banner list...!'));
        } else {
            //将指定id所有的通讯录返回给客户端
            logger.debug("Get contactlist successfully...!");
            if (banner == null) {
                var data = new Array();
                res.json(messageUtil.composeSucceededMessage(req, null, {'banner': data}));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, {'banner': banner.banner}));
            }
        }
    });
};

/**
 * 获取我的消息列表
 */
exports.getMyMessageList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;
    var vcode = req.cparams.vcode;

    systemService.getMyMessageListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get user message list...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var list = result[0];
            if (Number(vcode) > 1499) {
                list.forEach(function (temp) {
                    if (temp.content.questionDesc != null) {
                        switch (temp.content.contentType) {
                            //case 'myQuestion':
                            //    temp.content.questionDesc = '我的发布：' + temp.content.questionDesc;
                            //    break;
                            //case 'myFollowup':
                            //    temp.content.questionDesc = '我的收藏：' + temp.content.questionDesc;
                            //    break;
                            case 'myReply':
                                temp.content.questionDesc = '我的回复：' + temp.content.questionDesc;
                                break;
                            //case 'myThank':
                            //    temp.content.questionDesc = '被感谢：' + temp.content.questionDesc;
                            //    break;
                            case 'activity':
                                temp.content.questionDesc = '邻里活动：' + temp.content.questionDesc;
                                break;
                        }
                    }
                })
            }

            var data = {
                unReadNum: result[1],
                messages: result[0]
            };

            res.json(messageUtil.composeSucceededMessage(req, null, data))
        }
    });
};

/**
 * 获取运营推送消息列表
 * @param req
 * @param res
 */
exports.getOperateMessage = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    systemService.getOperateMessageService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getOperateMessage' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getOperateMessage' + err.message));
        } else {
            var data = {
                unReadNum: result[1],
                messages: result[0]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data))
        }
    })
};

/**
 * 清空回复通知消息
 * @param req
 * @param res
 */
exports.emptyMyMessage = function (req, res) {
    var token = req.params.token;
    systemService.emptyMyMessageService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when emptyMyMessageService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when emptyMyMessageService...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 清空运营推送消息
 * @param req
 * @param res
 */
exports.emptyOperateMessage = function (req, res) {
    var token = req.params.token;

    systemService.emptyOperateMessageService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when emptyOperateMessage...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when emptyOperateMessage...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.emptyUnReadMessage = function (req, res) {
    var token = req.params.token;

    systemService.emptyUnReadMessageService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when emptyUnReadMessage...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when emptyUnReadMessage...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.emptyUnReadOperateMessage = function (req, res) {
    var token = req.params.token;

    systemService.emptyUnReadOperateMessageService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when emptyUnReadOperateMessage...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when emptyUnReadOperateMessage...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.deleteReplyMessage = function (req, res) {
    var id = req.params.id;

    systemService.deleteReplyMessageService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteReplyMessage...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when deleteReplyMessage...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.deleteOperateMessage = function (req, res) {
    var id = req.params.id;

    systemService.deleteOperateMessageService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteOperateMessage...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when deleteOperateMessage...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 设置消息已读
 */
exports.setMessageAsRead = function (req, res) {
    var questionId = req.params.questionId;
    var token = req.params.token;

    systemService.setMessageAsReadService(token, questionId, function (err, result) {
        if (err) {
            logger.error('Exception happened when set message readFlag...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when set message readFlag...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 设置运营推送消息已读
 * @param req
 * @param res
 */
exports.setOperateMessageAsRead = function (req, res) {
    var messageId = req.params.messageId;
    var token = req.params.token;
    var clickSource = req.params.clickSource;

    systemService.setOperateMessageAsReadService(token, clickSource, messageId, function (err, result) {
        if (err) {
            logger.error('Exception happened when setOperateMessageAsRead...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when setOperateMessageAsRead...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 用户反馈
 */
exports.postFeedback = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    systemService.postFeedbackService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when post app feedback...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when post app feedback...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '反馈成功，请等待处理结果', null));
        }
    })
};

exports.getFeedbackList = function (req, res) {
    var communityId = req.params.communityId;

    systemService.getFeedbackListService(communityId, function (err, results) {
        if (err) {
            logger.error('Exception happened whengetFeedbackList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getFeedbackList...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getAppConfig = function (req, res) {
    var code = req.cparams.vcode;

    var data = {
        thirdPartyOn: thirdPartyOn,              //第三方登录开关
        refreshInterval: refreshInterval,        //刷新间隔
        searchCommunityOn: searchCommunityOn,    //搜索小区开关
        restHostIp: restHostIp,
        customerMessage: customerMessage,
        logoShow: logoShow
    };

    if (Number(code) >= 1500) {
        data.thirdPartyOn = false
    }

    res.json(messageUtil.composeSucceededMessage(req, null, data))
};

exports.postAppStartInfo = function (req, res) {
    var input = req.body;
    systemService.postAppStartInfoService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened whengetFeedbackList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when postAppStartInfo...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}

exports.postDeviceInfo = function (req, res) {
    var input = req.body;
    systemService.postDeviceInfoService(input, function (err, result) {
        res.json(messageUtil.composeSucceededMessage(req, null, null));
    })
};

exports.getMessageChatList = function (req, res) {
    var token = req.params.token;
    if (req.cparams != null) {
        var vCode = req.cparams.vcode;
    }
    systemService.getMessageChatListService(token, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMessageChatList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = new Array();
            data.push(result[0]);
            data.push(result[1]);
            //data.push(result[1]);

            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

// 取得环信聊天记录历史，1小时前
exports.getHxChatMessagesDownLoadUrl = function (req, res) {
    var ymdh = "2017111507";
    systemService.getHxChatMessagesDownLoadUrl(ymdh, function (err, data) {
        if (err) {
            logger.error('Exception happened when exportChatMessageListService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    });
};

/* 聊天记录导出：环信支持app把聊天记录通过REST接口导出 */
exports.exportIMChatMessageList = function (req, res) {//TODO: 完善该接口
    var token = req.params.token;


    //TODO: 引进 node-schedule
    /*logger.debug('1>>>>>>Exception happened when getIMChatMessageList...!');
     var schedule = require('node-schedule');
     var rule = new schedule.RecurrenceRule();
     //rule.minute = 42;
     rule.second = 30;
     var j = schedule.scheduleJob(rule, function(){
     logger.debug('2>>>>>>Exception happened when getIMChatMessageList...!');

     console.log('我在这里处理了某些事情...');
     });*/

    systemService.exportChatMessageListService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getIMChatMessageList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = new Array();
            data.push(result[0]);
            data.push(result[1]);
            //data.push(result[1]);

            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.getHotKeywords = function (req, res) {

    var token = req.params.token;

    systemService.getHotKeywordsService(token, function (err, results) {
        if (err) {
            logger.error('Exception happened when getHotKeywords...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getHotKeywords...!'));
        } else {
            logger.debug("getHotKeywords successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
}


//=========================================== Web后台管理 ============================================
/**
 * system-controller.js
 * 获取所有的短信记录
 * author:chenjinzhuan
 */
exports.getShortMessageList = function (req, res) {
    systemService.getShortMessageListService(function (err, results) {
        if (err) {
            logger.error('Exception happened when getShortMessageRecord...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getShortMessageRecord...!'));
        } else {
            logger.debug("getShortMessageRecord successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};


/**
 * TODO:
 * 获取所有IM的短信记录
 */
exports.getChatMessageList = function (req, res) {
    logger.debug(">>>>>>getChatMessageList()");//TODO:logger没有打印出来?
    systemService.getChatMessageListService(function (err, results) {//modify
        if (err) {
            logger.error('Exception happened when getChatMessageRecord...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getChatMessageRecord...!'));
        } else {
            logger.debug("getChatMessageRecord successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
            //res.json(messageUtil.composeSucceededMessage(req, null, results.get(1)));
        }
    });
};


/**
 * TODO:
 * 获取所有IM的短信记录
 */
exports.searchChatMessage = function (req, res) {
    logger.debug(">>>>>>searchChatMessage()");
    var input = req.body;

    systemService.searchChatMessageListService(input, function (err, results) {//modify
        if (err) {
            logger.error('Exception happened when searchChatMessage...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when searchChatMessage...!'));
        } else {
            logger.debug("searchChatMessage() successfully...!");
            var array = new Array();
            //array.push(results[0]);
            //array.push(results[1]);

            array = results[0];
            array.concat(results[1]);

            array = distinct(array);

            //res.json(messageUtil.composeSucceededMessage(req, null, results));
            res.json(messageUtil.composeSucceededMessage(req, null, array));
            //res.json(messageUtil.composeSucceededMessage(req, null, results.get(1)));
        }
    });
};


/**
 * TODO:
 * 搜索某人和他的一位朋友的聊天记录
 */
exports.searchChatLogByTwoUser = function searchChatLogByTwoUser(req, res) {//TODO:重命名为searchChatLogByTwoUserController
    logger.debug(">>>>>>searchChatLogByTwoUser()");
    var input = req.body;

    systemService.searchChatLogByTwoUserService(input, function (err, results) {//modify
        if (err) {
            logger.error('Exception happened when searchChatMessage...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when searchChatMessage...!'));
        } else {
            logger.debug("searchChatLogByTwoUser() successfully...!");

            /*distinct*/
            //var array = new Array();
            //array = results[0];
            //array.concat(results[1]);
            //array = distinct(array);
            //res.json(messageUtil.composeSucceededMessage(req, null, array));

            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};


/**
 * system-controller.js
 * 搜索短信
 * author:chenjinzhuan
 */
exports.searchShortMessage = function (req, res) {
    var input = req.body;

    systemService.searchShortMessageService(input, function (err, results) {
        if (err) {
            logger.error('Exception happened when searchShortMessage...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when searchShortMessage...!'));
        } else {
            logger.debug("searchShortMessage successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

/**
 * （用环信）发送IM消息
 */
exports.sendMessageByCustom = function (req, res) {
    var communityId = req.body.communityId;
    var msg = req.body.msg;

    systemService.sendMessageByCustomService(communityId, msg, function (err, result) {
        if (err) {
            logger.error('Exception happened when sendMessageByCustom...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when sendMessageByCustom...!'));
        } else {
            logger.debug("sendMessageByCustom successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};


/**
 * TODO:getInterestList
 */
exports.getInterestList22 = function (req, res) {
    logger.debug(">>>>>>22.getInterestList()");//TODO:logger没有打印出来?
    //var startPage = req.params.startPage;
    var inputFrom = req.params.inputFrom;
    logger.debug("inputFrom:");
    logger.debug(inputFrom);

    restClient.get('http://' + RecommendHost + ':8007?recbyuid2=' + inputFrom, function (data, response) {//old,

        if (response.statusCode == 200 && data != null && data != 'unknown') {

            var jsonData = JSON.parse(data);
            res.json(messageUtil.composeSucceededMessage(req, null, jsonData));//TODO: json测试

        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, []));
        }
    }).on('error', function (err) {
        logger.error('else.restClient error---' + err.message);
        res.json(messageUtil.composeSucceededMessage(req, null, []));
    });

};


/**
 * TODO:getInterestList
 */
exports.interestGeorge = function (req, res) {
    logger.debug(">>>>>>2.getInterestList()");//TODO:logger没有打印出来?

    /* 1）读取json文件 */
    /*fs.writeFileSync('./output.json',JSON.stringify({a:1,b:2}));
     //var JsonObj=JSON.parse(fs.readFileSync('./output.json'));
     var JsonObj=JSON.parse(fs.readFileSync('./interest.json'));
     //console.log(JsonObj);
     logger.debug(JsonObj);
     res.json(messageUtil.composeSucceededMessage(req, null, JsonObj));*/


    /* 2）httpclient访问rest API TODO：为啥无法用这种方式来访问？*/
    //http.get('http://codestudy.sinaapp.com', function (response) {
    //http.get('http://192.168.1.123:8003/?recbyuid=54fbfda475b5b1be32b917cf', function (response) {
    /*http.get('http://localhost:3000/rest/v1.0/backoffice/Systems/getShortMessageList', function (response) {
     logger.debug(">>>>>>1.response:");
     logger.debug(response);
     var data = response.data;

     res.json(messageUtil.composeSucceededMessage(req, null, data));
     });*/


    /* 3）restClient */
    restClient.get('http://192.168.1.123:8003/?recbyuid=54fbfda475b5b1be32b917cf', function (data, response) {//old,
        //restClient.get('http://192.168.1.123:8002/?data=周末去哪里玩啊', function (data, response) {
        //restClient.get('http://192.168.1.123:8003/?usersbytag=%E6%B1%BD%E8%BD%A6&community=549968e5bc537bb017132f01', function (data, response) {

        //restClient.get('http://localhost:12306/', function (data, response) {
        //restClient.get('http://localhost:3000/rest/v1.0/backoffice/Systems/getShortMessageList', function (data, response) {
        //restClient.get('http://api.map.baidu.com/place/v2/search?&query=%27%20+%20keyword%20+%20%27&region=%E4%B8%8A%E6%B5%B7&scope=2&output=json&ak=AvRqTglpaKICTZ5iwyn06KZj&radius=1000&page_size=20&page_num=0', function (data, response) {

        logger.debug("》》》》data begin:");
        logger.debug(data);
        logger.debug("》》》》data end:");

        if (response.statusCode == 200 && data != null && data != 'unknown') {
            logger.debug("if.response:");
            logger.debug("response.statusCode:");
            logger.debug(response.statusCode);
            logger.debug("data:");
            logger.debug(data);

            //var uList = JSON.parse(data).ids;
            //res.json(messageUtil.composeSucceededMessage(req, null, uList));
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, []));
        }
    }).on('error', function (err) {
        logger.error('else.restClient error---' + err.message);
        res.json(messageUtil.composeSucceededMessage(req, null, []));
    });


    /*systemService.getChatMessageListService(function (err, results) {//modify
     if (err) {
     logger.error('Exception happened when getChatMessageRecord...!');
     res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getChatMessageRecord...!'));
     } else {
     logger.debug("getChatMessageRecord successfully...!");
     res.json(messageUtil.composeSucceededMessage(req, null, results));
     //res.json(messageUtil.composeSucceededMessage(req, null, results.get(1)));
     }
     });*/


    /* http.get('http://localhost:3000/rest/v1.0/backoffice/Systems/getShortMessageList', {
     //headers: {'Content-Type': 'application/json;charset=utf-8','Access-Control-Allow-Origin': 'http://192.168.1.123'}
     headers: {'Content-Type': 'application/json;charset=utf-8'}
     }).success(function (data) {
     //$scope.shortMessageList = data;

     logger.debug("data:");
     logger.debug(data);

     }).error(function () {
     });
     */
    /*http.get('http://localhost:3000/rest/v1.0/backoffice/Systems/getShortMessageList', function (err, results) {//modify
     if (err) {
     logger.error('Exception happened when getChatMessageRecord...!');
     res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getChatMessageRecord...!'));
     } else {
     logger.debug("getChatMessageRecord successfully...!");
     res.json(messageUtil.composeSucceededMessage(req, null, results));
     //res.json(messageUtil.composeSucceededMessage(req, null, results.get(1)));
     }
     });*/

    /*req.get("http://www.baidu.com/", function(res) {
     //console.log("Got response: " + res.statusCode);
     logger.debug("Got response:");
     logger.debug(res.statusCode);

     });*/


    /*systemService.getChatMessageListService(function (err, results) {//modify
     if (err) {
     logger.error('Exception happened when getChatMessageRecord...!');
     res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getChatMessageRecord...!'));
     } else {
     logger.debug("getChatMessageRecord successfully...!");
     res.json(messageUtil.composeSucceededMessage(req, null, results));
     //res.json(messageUtil.composeSucceededMessage(req, null, results.get(1)));
     }
     });*/
};


/**
 * 上传图片
 * @param req
 * @param res
 */
exports.uploadImages = function (req, res) {
    var imagePath1 = req.files.imgFile.path;

    //fdfsClient.upload(imagePath1, {ext: 'png'}, function (err, fileId) {
    //    if (err) {
    //        logger.error('Failed to upload image to fastDfs');
    //        res.json({"error": 1, "message": "上传图片失败", "url": ""})
    //    } else {
    //        logger.info(fileId);
    //        var array = fileId.split('.');
    //
    //        var url = fastDfsHostIp + '/' + array[0] + '_400-400.png';
    //        res.json({"error": 0, "message": "ok", "url": url})
    //    }
    //});

    qiniuUtil.uploadFile(imagePath1, function (err, result) {

        if (err) {
            logger.error('Failed to upload image to fastDfs');
            res.json({"error": 1, "message": "上传图片失败", "url": ""})
        } else {
            logger.info(result);

            var url = 'http://' + imgHost + result + jpgFormat;
            res.json({"error": 0, "message": "ok", "url": url})
        }

        fs.unlink(imagePath1);
    });
};

exports.oldUploadImages = function (req, res) {

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload oldUploadImages... - ' + err.message));
        } else {
            var urls = [];

            for (i = 0; i < images.length; i++) {
                if (images[i] != null) {
                    urls.push(images[i]);
                }
            }
            res.json(messageUtil.composeSucceededMessage(req, null, urls))
        }
    })
}

exports.getDetailOfSpecialTopic = function (req, res) {
    var topicId = req.params.topicId;
    var token = req.params.token;


    systemService.getDetailOfSpecialTopicService(token, topicId, function (err, result) {
        if (err) {
            logger.error('Exception happened when get a SpecialTopic ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getTopicReply = function (req, res) {
    var topicId = req.params.topicId;
    var page = req.params.pageNo;
    var token = req.params.token;
    var vCode = req.cparams.vcode;
    var clickSource = req.cparams.clickSource;

    systemService.getTopicReplyService(page, topicId, token, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when get a getTopicReply ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: topicId,
                    type: 3,
                    clickSource: clickSource,
                    typeDesc: '专题',
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};

exports.getSpecialTopicList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    systemService.getSpecialTopicListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get a getSpecialTopicList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.postSpecialTopicComment = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    systemService.postSpecialTopicCommentService(input, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when postSpecialTopicComment ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));

            var topic = result[1];
            toolUtil.filteringSensitiveWords(topic._id, topic.comments[topic.comments.length - 1]._id, input.commentDesc, 'topic');

            if (input.uList != null && typeof input.uList == 'string') {
                input.uList = [input.uList];
            }

            //@功能
            if (input.uList != null && input.uList.length > 0 && input.commentDesc.indexOf(atFlag) != -1) {
                questionService.replyAtService(topic, topic.comments[topic.comments.length - 1]._id, input.uList, 'topic', token, input.commentDesc);

                //推送
                toolUtil.putMessageQAMQ({
                    msgType: 'reply',
                    isExistAt: 1,
                    atUidList: input.uList,
                    replyUid: token,
                    topicId: topic._id + '',
                    replyId: topic.comments[topic.comments.length - 1]._id + '',
                    replyDesc: input.commentDesc,
                    contentType: 'specialTopic',
                    isAsk: 0
                });
            }
        }
    })
};

exports.postSpecialTopic = function (req, res) {
    var input = req.body;

    systemService.postSpecialTopicService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when postSpecialTopic ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}

exports.createSpecialNews = function (req, res) {
    var input = req.body;

    systemService.createSpecialNewsService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when createSpecialNews ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.removeNews = function (req, res) {
    var newsId = req.params.newsId;

    systemService.removeNewsService(newsId, function (err, result) {
        if (err) {
            logger.error('Exception happened when removeNews ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}

exports.getSpecialNewsList = function (req, res) {
    var communityId = req.params.communityId;

    systemService.getSpecialNewsListService(communityId, function (err, results) {
        if (err) {
            logger.error('Exception happened when getSpecialNewsListService ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.confirmOrder = function (req, res) {
    var input = req.body.newsId;

    systemService.confirmOrderService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when confirmOrder ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getPushUserList = function (req, res) {
    var opt = req.body;

    systemService.getPushUserListService(opt, function (err, results) {
        if (err) {
            logger.error('Exception happened when getPushUserList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.confirmPush = function (req, res) {

    var input = req.body;

    //logger.info(input);

    //个推
    var content = {
        type: 1,
        flag: 2,
        openType: input.openType,
        contentId: input.contentId,
        createdBy: input.createdBy,
        desc: input.desc,
        url: input.url
    };
    var pushData = {
        uList: input.uList,
        content: content,
        ip: req.headers['X-Real-IP'],
        tag: input.tag,
        type: 'operate'
    };
    toolUtil.putMessageGetuiPushMQ(pushData);

    res.json(messageUtil.composeSucceededMessage(req, null, null));
};

exports.confirmGroupPush = function (req, res) {
    //logger.debug(req.body);
    systemService.confirmGroupPushService(req, function (err, results) {
        if (err) {
            logger.error('Exception happened when confirmGroupPush ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            //logger.debug(req);
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.confirmPushByModerator = function (req, res) {
    var input = req.body;
    logger.debug(input);
    //var opt = {
    //    community: input.communityId
    //}

    systemService.getPushUserListService(input, function (err, results) {
        if (err) {
            logger.error('Exception happened when getPushUserList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            //个推
            var content = {
                type: 1,
                flag: 2,
                openType: input.openType,
                contentId: input.contentId,
                createdBy: input.createdBy,
                desc: input.desc,
                url: input.url
            };
            var pushData = {
                uList: results[0],
                content: content,
                ip: req.headers['X-Real-IP'],
                tag: input.tag,
                type: 'operate'
            };
            logger.debug(pushData);
            toolUtil.putMessageGetuiPushMQ(pushData);

            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })

};

exports.getAllCommunityTopic = function (req, res) {
    var communityId = req.params.communityId;
    var status = req.params.status;

    systemService.getAllCommunityTopicService(communityId, status, function (err, results) {
        if (err) {
            logger.error('Exception happened when getAllCommunityTopic ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.setTopicStatus = function (req, res) {
    var input = req.body;

    systemService.setTopicStatusService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when setTopicStatus ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

exports.getTopicById = function (req, res) {
    var id = req.params.id;

    systemService.getTopicByIdService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when getTopicById ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
}

exports.getAllCommunityStatistics = function (req, res) {
    systemService.getAllCommunityStatisticsService(function (err, result) {
        if (err) {
            logger.error('Exception happened when getAllCommunityTopic ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                noReply: result[0],
                report: result[1],
                authentication: result[2],
                feedback: result[3],
                supplement: result[4],
                user: result[5],
                question: result[6],
                reply: result[7],
                noReplyAt: result[8]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.getCommunityActivityList = function (req, res) {


    var communityId = req.params.communityId;

    systemService.getCommunityActivityListService(communityId, function (err, results) {
        if (err) {
            logger.error('Exception happened when getCommunityActivityList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getNotActiveUser = function (req, res) {
    var communityId = req.params.communityId;

    systemService.getNotActiveUserService(communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getNotActiveUser ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var uList = result[2];
            res.json(messageUtil.composeSucceededMessage(req, null, uList));
        }
    });
};

exports.acceptSmsRt = function (req, res) {

    console.log(req.url);

    var result = req.url.split('?')[1].split('&');

    var input = {
        messageId: result[3].split('=')[1],
        status: result[4].split('=')[1],
        errCode: result[5].split('=')[1]
    };
    console.log(input);
    systemService.acceptSmsRtService(input, function (err, result) {
        res.json(messageUtil.composeSucceededMessage(req, null, null));
    })
};

exports.deleteTopic = function (req, res) {
    var id = req.params.id;

    systemService.deleteTopicService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteTopic ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.generateAllTopics = function (req, res) {

    systemService.getAllTopic(function (err, list) {
        if (err) {
            logger.error('Exception generateAllTopics HTML ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            for (var i in list) {
                var obj = list[i];
                //var date = moment(obj.dateCreated).format('YYYY-MM-DD HH:mm');
                //var header = '<B><font  size="5">' + obj.title + '</font></B><br>' + date + '<br>';
                //obj.desc = header + obj.desc;

                systemService.generateTopicHtml(obj, topicPath);
            }
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
}

exports.shortUrl = function (req, res) {
    var url = req.body.url;

    systemService.shortUrlService(url, function (err, result) {
        if (err) {
            logger.error('Exception happened when shortUrlService' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.generatePromotionCode = function (req, res) {
    var input = req.body;

    systemService.generatePromotionCodeService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when generatePromotionCode' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getPromotionCodeList = function (req, res) {
    var input = req.body;

    systemService.getPromotionCodeListService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getPromotionCodeList' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.getPromotionCodeDateCreated = function (req, res) {

    systemService.getPromotionCodeDateCreatedService(function (err, result) {
        if (err) {
            logger.error('Exception happened when getPromotionCodeDateCreated' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = {
                createDate: result[0],
                expirationDate: result[1]
            };

            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.setPromotionCodeOwner = function (req, res) {
    var input = req.body;
    systemService.setPromotionCodeOwnerService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when setPromotionCodeOwner' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.receiveOfflineMessage = function (req, res) {
    var input = req.body;
    logger.info(input)

    systemService.receiveOfflineMessageService(input, function (err, result) {
        var md5Str = md5(input.callId + '654321' + 'true');
        var data = {
            "callId": input.callId,
            "accept": "true",//表明接受了此推送.
            "reason": "",//可选,accept为false时使用
            "security": md5Str//签名. 格式如下: md5(callId+约定的key+"true"),约定key为654321
        };
        res.json(data);
    })
};

exports.setOfflineMessageAsRead = function (req, res) {
    var huanxinId = req.params.huanxinId;
    var token = req.params.token;

    systemService.setOfflineMessageAsReadService(token, huanxinId, function (err, result) {
        if (err) {
            logger.error('Exception happened when setOfflineMessageAsRead' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};
exports.appErrorLog = function (req, res) {
    var errorLog = req.body;
    logger.info(errorLog);
    if (errorLog.errorMsg)
        systemService.appErrorLogService(errorLog, function (err, result) {

        })
    res.json(messageUtil.composeSucceededMessage(req, null, null));
};
exports.getAppErrorLogList = function (req, res) {
    var input = req.body;
    systemService.getAppErrorLogListService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getAppErrorLog' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.getSystemConfig = function (req, res) {

    var result = {
        //resUrl: fastDfsHostIp
        resUrl : imgHost
    };

    res.json(messageUtil.composeSucceededMessage(req, null, result));

};
//getPushGroupList
exports.getPushGroupList = function (req, res) {
    var opt = req.body;
    logger.debug(opt);
    systemService.getPushGroupListService(opt, function (err, results) {
        if (err) {
            logger.error('Exception happened when getPushGroupList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};



exports.getTopicByFilter = function (req, res) {
    var opt = req.body;
    logger.debug(opt);
    systemService.getTopicByFilterService(opt, function (err, results) {
        if (err) {
            logger.error('Exception happened when getTopicByFilter ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getTopicByFilterPaging = function (req, res) {
    var opt = req.body;
    var pageSize = req.params.pagesize;
    var pageNumber = req.params.pagenumber;
    logger.debug(opt);
    systemService.getTopicByFilterPagingService(pageSize,pageNumber,opt, function (err, results) {
        if (err) {
            logger.error('Exception happened when getTopicByFilter ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                totalPage: results[0],
                topicList: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};